// KnowledgePackageServiceImpl.java - 完整实现
package com.example.gymlearning.service.impl;

import com.example.gymlearning.dto.KnowledgePackageDTO;
import com.example.gymlearning.entity.KnowledgePackage;
import com.example.gymlearning.entity.KnowledgePoint;
import com.example.gymlearning.mapper.KnowledgePackageMapper;
import com.example.gymlearning.mapper.KnowledgePointMapper;
import com.example.gymlearning.service.KnowledgeModuleService;
import com.example.gymlearning.service.KnowledgePackageService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service("knowledgePackageService")
public class KnowledgePackageServiceImpl implements KnowledgePackageService {

    @Resource
    private KnowledgePackageMapper knowledgePackageMapper;

    @Resource
    private KnowledgePointMapper knowledgePointMapper;

    @Resource
    private KnowledgeModuleService knowledgeModuleService;

    @Override
    public List<KnowledgePackageDTO> getAllPackagesWithStats() {
        List<KnowledgePackage> packages = knowledgePackageMapper.selectAll();
        return packages.stream().map(this::convertToDTO).collect(Collectors.toList());
    }

    @Override
    public List<KnowledgePackageDTO> getPackagesByModule(Long moduleId) {
        List<KnowledgePackage> packages = knowledgePackageMapper.selectByModuleId(moduleId);
        return packages.stream().map(this::convertToDTO).collect(Collectors.toList());
    }

    @Override
    public KnowledgePackageDTO getPackageById(Long id) {
        KnowledgePackage pkg = knowledgePackageMapper.selectById(id);
        if (pkg == null) {
            return null;
        }
        return convertToDTO(pkg);
    }

    @Override
    public Page<KnowledgePackageDTO> getAllPackagesWithStats(int page, int size) {
        PageHelper.startPage(page, size);
        Page<KnowledgePackage> packagesPage = knowledgePackageMapper.selectAllForPage();

        Page<KnowledgePackageDTO> resultPage = new Page<>(page, size);
        resultPage.setTotal(packagesPage.getTotal());

        List<KnowledgePackageDTO> dtoList = packagesPage.getResult().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        resultPage.addAll(dtoList);

        return resultPage;
    }

    @Override
    public Page<KnowledgePackageDTO> getPackagesByModule(Long moduleId, int page, int size) {
        PageHelper.startPage(page, size);
        Page<KnowledgePackage> packagesPage = knowledgePackageMapper.selectByModuleIdForPage(moduleId);

        Page<KnowledgePackageDTO> resultPage = new Page<>(page, size);
        resultPage.setTotal(packagesPage.getTotal());

        List<KnowledgePackageDTO> dtoList = packagesPage.getResult().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        resultPage.addAll(dtoList);

        return resultPage;
    }

    @Override
    public Long getNextPackageId(Long currentPackageId) {
        return knowledgePackageMapper.findNextPackageId(currentPackageId);
    }

    @Override
    public KnowledgePackageDTO getById(Long id) {
        return this.getPackageById(id);
    }

    // 添加缺失的方法实现
    @Override
    public Page<KnowledgePackageDTO> getPackagesByClass(Long classId, int page, int size) {
        PageHelper.startPage(page, size);
        Page<KnowledgePackage> packagesPage = knowledgePackageMapper.selectByClassIdForPage(classId);

        Page<KnowledgePackageDTO> resultPage = new Page<>(page, size);
        resultPage.setTotal(packagesPage.getTotal());

        List<KnowledgePackageDTO> dtoList = packagesPage.getResult().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        resultPage.addAll(dtoList);

        return resultPage;
    }

    @Override
    public Page<KnowledgePackageDTO> getPackageById(Long packageId, int page, int size) {
        PageHelper.startPage(page, size);
        Page<KnowledgePackage> packagesPage = knowledgePackageMapper.selectByIdForPage(packageId);

        Page<KnowledgePackageDTO> resultPage = new Page<>(page, size);
        resultPage.setTotal(packagesPage.getTotal());

        List<KnowledgePackageDTO> dtoList = packagesPage.getResult().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        resultPage.addAll(dtoList);

        return resultPage;
    }


    @Override
    public Page<KnowledgePackageDTO> getPackagesByModuleWithPagination(Long moduleId, int page, int size) {
        PageHelper.startPage(page, size);
        List<KnowledgePackageDTO> packages = knowledgePackageMapper.selectPackagesByModuleId(moduleId);
        return (Page<KnowledgePackageDTO>) packages;
    }

    @Override
    public long countByModule(Long moduleId) {
        Long count = knowledgePackageMapper.countByModuleId(moduleId);
        return count == null ? 0L : count;
    }

    /**
     * 将 KnowledgePackage 实体转换为 KnowledgePackageDTO
     */
    private KnowledgePackageDTO convertToDTO(KnowledgePackage pkg) {
        KnowledgePackageDTO dto = new KnowledgePackageDTO();
        dto.setId(pkg.getId());
        dto.setName(pkg.getName());
        dto.setDescription(pkg.getDescription());
        dto.setModuleId(pkg.getModuleId());

        // 设置模块名称
        String moduleName = knowledgeModuleService.getModuleById(pkg.getModuleId()).getName();
        dto.setModuleName(moduleName);

        // 获取该知识包下的所有知识点
        List<KnowledgePoint> points = knowledgePointMapper.selectByPackageId(pkg.getId());
        dto.setKnowledgePoints(points);

        // 计算统计信息
        calculatePackageStats(dto, points);

        return dto;
    }

    /**
     * 计算知识包的统计信息
     */
    private void calculatePackageStats(KnowledgePackageDTO dto, List<KnowledgePoint> points) {
        dto.setPointCount(points.size());

        // 计算总时长和总经验值
        int totalDuration = points.stream().mapToInt(KnowledgePoint::getBaseDuration).sum();
        int totalExperience = points.stream().mapToInt(KnowledgePoint::getBaseExperience).sum();
        dto.setTotalDuration(totalDuration);
        dto.setTotalExperience(totalExperience);

        // 计算各难度级别的知识点数量
        long beginnerCount = points.stream()
                .filter(point -> "BEGINNER".equalsIgnoreCase(point.getDifficultyLevel()))
                .count();
        long intermediateCount = points.stream()
                .filter(point -> "INTERMEDIATE".equalsIgnoreCase(point.getDifficultyLevel()))
                .count();
        long advancedCount = points.stream()
                .filter(point -> "ADVANCED".equalsIgnoreCase(point.getDifficultyLevel()))
                .count();

        dto.setBeginnerPoints((int) beginnerCount);
        dto.setIntermediatePoints((int) intermediateCount);
        dto.setAdvancedPoints((int) advancedCount);
    }
}